package com.nd.rj.common.login.communication;

import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.telephony.TelephonyManager;

import com.common.android.utils.httpRequest.HttpRequest;
import com.common.android.utils.httpRequest.IHttpRequest;
import com.nd.rj.common.R;
import com.nd.rj.common.login.GlobalSetting;
import com.nd.rj.common.login.entity.RegConst;
import com.product.android.business.ApplicationVariable;
import com.product.android.business.bean.UserInfo;
import com.product.android.business.config.Configuration;



/**
 * uap同步类
 * 
 * @author yiyang
 */
public class uapCom {
    // 请求地址定义
    private static final String BASE_URL_OUT = Configuration.getOAPServiceUrl(); // 外网地址
    // private static final String BASE_URL_IN = "http://192.168.94.19/uapsapp/"; // 内网地址

    // 请求地址定义，https
    private static final String BASE_HTTPS_URL_OUT = Configuration.getOAPServiceUrl(); // 外网地址
    // private static final String BASE_HTTPS_URL_IN = "http://192.168.94.19/uapsapp/"; // 内网地址

    // // 注册地址
    // private final String REG_UAP ="https://reg.uap.91.com/";

    // 登陆
    private static final String LOGIN_URL = "login";
    /**头链接*/
    private static final String BASE_REG_URL = "https://uap.99.com/";
//    private static final String BASE_REG_URL = "http://192.168.94.19/uaps/";
    // 注册
    private final String USER_URL = "user";
    
    // 短信验证码
    private final String SEND_CODE = "sapp/sendcode";
    /**检查是否可注册*/
    private final String PHONE_ISREG = "ndsoap/chkaliasexists";
    /**重新绑定手机号*/
    private final String CHANGE_PHONE = "ndsoap/changesecphone";
    /**修改密码*/
    private final String CHANGE_PWD= "user/changepwd";
    /**注册发手机验证码*/
    private final String REG_SEND_CODE= "ndsoap/alias_sendcode";
    /**手机注册*/
    private final String ALIAS_REG_PHONE= "ndsoap/alias_regphone_autopwd";
    // 手机注册
    private final String REG_PHONE = "sapp/regphone";

    // 注销
    private static final String LOGOUT = "logout/%d?sid=%s";

    // 获取无线sid
    private final String CHARGE_URL = "login/charge?sid=%s";

    // 获取用户简介
    private final String GET_USER_URL = "user/%d?sid=%s";

    // SESSION 验证
    private final String CHECKSESSION_URL = "checksession?sid=%s";

    // 见http://192.168.19.197/wiki2/doku.php?id=star_app_server
    // cookie换票据
    private final String GET_TICKET_BY_COOKIE_URL = "login/cookie";
    // 票据登录
    private final String TICKET_URL = "login/ticket";
    // private static final String USER_URL = "user";
    // private static final String FRIEND_URL = "friend";
    // 错误码
    // private static final int ERROR_USER_NOT_EXISTS = 404;// 用户不存在
    // private static final int ERROR_PASSWORD_ERROR = 403;// 认证失败/密码错误
    // private static final int ERROR_OUT_LIMIT = 423;// 用户登录限制
    
    // TODO 未确定接口
    //取帐号状态接口
    private final String GET_ACCOUNT_STATUS = "";

    private IHttpRequest mHttpRequest;

    private static uapCom mCom;
    private Context mContext;
    private String mAppid;
//    private String mUapAppid;

    private uapCom(Context ctx) {
        mHttpRequest = HttpRequest.getInstance(ctx);
        mContext = ctx;
        mAppid = GlobalSetting.getInstance(ctx).getAppid();
//        mUapAppid = GlobalSetting.getInstance(ctx).getUapAppid();
    }

    public static uapCom getInstance(Context ctx) {
        if (mCom == null)
            mCom = new uapCom(ctx);
        return mCom;
    }

    /**
     * uap请求地址
     * 
     * @return
     */
    private String getBaseHttpUrl() {
        int env = GlobalSetting.getInstance(mContext).getNetworkEnv();
        if (env == GlobalSetting.NETWORK_IN) {
            return BASE_URL_OUT;
        } else if (env == GlobalSetting.NETWORK_OUT) {
            return BASE_URL_OUT;
        } else {
            return BASE_URL_OUT;
        }
    }

    /**
     * uap请求地址，HTTPS
     * 
     * @return
     */
    private String getBaseHttpsUrl() {
        int env = GlobalSetting.getInstance(mContext).getNetworkEnv();
        if (env == GlobalSetting.NETWORK_IN) {
            return BASE_HTTPS_URL_OUT;
        } else if (env == GlobalSetting.NETWORK_OUT) {
            return BASE_HTTPS_URL_OUT;
        } else {
            return BASE_HTTPS_URL_OUT;
        }
    }

    private String appendUapAppid(String url) {
        if (url.indexOf("?") > 0) {
            url += "&&appid=" + mAppid;
        } else {
            url += "?appid=" + mAppid;
        }
        return url;
    }

    /**
     * 用户登录
     * 
     * @param username
     * @param password
     * @return srecive
     * @return
     */
    public int userLogin(String username, String password, StringBuilder receive) {
        int ireturn = R.string.nd_uap_login_error;
        // 连接uap通讯
        JSONObject json = new JSONObject();
        try {
            json.put("appid", mAppid);
            json.put("password", password);
            json.put("username", username);
            // 是否启用rsa加密，可选值0|1，默认为0不启用；当值为1时，password值要设置为base64_encode(rsa_encode(password))
            json.put("rsa", "1");
            StringBuilder HttpUrl = new StringBuilder();
            HttpUrl.append(getBaseHttpUrl());
            HttpUrl.append(LOGIN_URL);
            ireturn = mHttpRequest.doPost(appendUapAppid(HttpUrl.toString()), json, receive);
            if (ireturn != HttpStatus.SC_OK) {
                switch (ireturn) {
                case HttpStatus.SC_BAD_REQUEST:
                    receive.delete(0, receive.length());
                    ireturn = R.string.nd_login_limit;
                    break;
                case HttpStatus.SC_FORBIDDEN:
                    receive.delete(0, receive.length());
                    ireturn = R.string.nd_login_psw_error;
                    break;
                case HttpStatus.SC_NOT_FOUND:
                    receive.delete(0, receive.length());
                    ireturn = R.string.nd_login_account_not_exists;
                    break;
                default:
                    _getResponseErrMsg(receive);
                    break;
                }
            } else
                ireturn = 0;
        } catch (JSONException e) {
            e.printStackTrace();
            ireturn = R.string.nd_json_error;
        } finally {
            json = null;
        }
        return ireturn;
    }

    /**
     * 用户注册
     * 
     * @param username
     * @param password
     * @param nickname
     * @return
     */
    public int userRegister(String username, String password, String nickname, String blowfish,
            StringBuilder receive) {
        int ireturn = R.string.nd_user_register_error;
        JSONObject send = new JSONObject();
        try {
            send.put("appid", mAppid);
            send.put("username", username);
            send.put("password", password);
            send.put("nickname", nickname);
            send.put("blowfish", blowfish);
            // 是否启用rsa加密，可选值0|1，默认为0不启用；当值为1时，password值要设置为base64_encode(rsa_encode(password))
            send.put("rsa", "1");
            String m_strURL = getBaseHttpUrl() + USER_URL;
            m_strURL = appendUapAppid(m_strURL);
            ireturn = mHttpRequest.doPost(m_strURL, send, receive);
            if (ireturn != HttpStatus.SC_CREATED) {
                _getResponseErrMsg(receive);
            } else
                ireturn = 0;
        } catch (JSONException e) {
            e.printStackTrace();
            ireturn = R.string.nd_json_error;
        }
        return ireturn;
    }

    /**
     * 发送短信验证码
     * 
     * @Title: sendCode
     * @author chenyw
     * @date 2012-6-18
     * @param @param appid
     * @param @param phone
     * @param @param receive
     * @param @return
     * @return int
     * @throws
     */
    public int sendCode(String phone, String type, StringBuilder receive) {
        int ireturn = R.string.nd_send_code_error;
        JSONObject send = new JSONObject();
        try {
            send.put("phone", phone);
            String m_strURL = getBaseHttpUrl() + SEND_CODE;
            m_strURL = appendUapAppid(m_strURL);
            ireturn = mHttpRequest.doPost(m_strURL, send, receive);
            if (ireturn != HttpStatus.SC_OK) {
                _getResponseErrMsg(receive);
            } else
                ireturn = 0;
        } catch (JSONException e) {
            e.printStackTrace();
            ireturn = R.string.nd_json_error;
        }
        return ireturn;
    }

    /**
     * 手机注册
     * 
     * @Title: sendCode
     * @author chenyw
     * @date 2012-6-18
     * @param @param appid
     * @param @param phone
     * @param @param receive
     * @param @return
     * @return int
     * @throws
     */
    public int regPhone(String phone, String password, String verifycode, String blowfish,
            StringBuilder receive) {
        int ireturn = R.string.nd_reg_phone_error;
        JSONObject send = new JSONObject();
        try {
            send.put("appid", mAppid);
            send.put("phone", phone);
            send.put("password", password);
            send.put("verifycode", verifycode);
            send.put("tag", Configuration.TAG_ID);
            send.put("blowfish", blowfish);

            String m_strURL = getBaseHttpUrl() + REG_PHONE;
            m_strURL = appendUapAppid(m_strURL);
            ireturn = mHttpRequest.doPost(m_strURL, send, receive);
            if (HttpStatus.SC_OK == ireturn) {
                ireturn = 0;
            } else if (ireturn != HttpStatus.SC_CREATED && ireturn != HttpStatus.SC_CONFLICT) {
                _getResponseErrMsg(receive);
            } else if (ireturn == HttpStatus.SC_CONFLICT) {
                ireturn = 1;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            ireturn = R.string.nd_json_error;
        }
        return ireturn;
    }

    /**
     * 判断是否可以注册 <br>
     * Created 2014-9-5 下午3:23:13
     * 
     * @param strPhone
     *            注册手机号
     * @return 200 可以注册 （1、用户不存在；2、多绑相关：当前登陆帐号允许绑定；3、用户没有绑定密宝手机）
     *         406 帐号格式不合法 
     *         409 其他原因导致无法注册
     * @author gpy
     */
    public int isRegistered(String strPhone) {
        try {
            JSONObject jsonSend = new JSONObject();
            jsonSend.put("phone", strPhone);
            String m_strURL = BASE_REG_URL + PHONE_ISREG;
            StringBuilder receive = new StringBuilder();
            int ireturn = mHttpRequest.doPost(m_strURL, jsonSend, receive);
            if (HttpStatus.SC_OK == ireturn || HttpStatus.SC_NOT_ACCEPTABLE == ireturn
                    || HttpStatus.SC_CONFLICT == ireturn) {
                return ireturn ;
            } else {
                return HttpStatus.SC_CONFLICT;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return HttpStatus.SC_CONFLICT;

    }
    

    /**
     * 注册发送手机短信验证码
     * <br>Created 2014-9-9 下午3:30:57
     * @param phone 手机号码，必须，11位整型
     * @param type  验证码类型，=4 发送手机注册验证码，必须
     * @param btype  注册类型，=1 通用手机注册
     * @param errorMessage 返回的消息
     * @return 200 发送成功 
     * 416 短信验证码类型为空或不合法/手机号码为空/手机号码不合法 
     * 206 手机已被绑定 
     * 406 发送短信验证码失败（别名手机已存在无法注册） 
     * 409 其他原因导致失败 
     * @author       gpy
    */
    public int regSendCode(String phone,int type,int btype,StringBuilder errorMessage) {
        int ireturn = R.string.nd_send_code_error;
        JSONObject send = new JSONObject();
        try {
            send.put("phone", phone);
            send.put("type", type);
            send.put("btype", btype);
            String m_strURL = BASE_REG_URL + REG_SEND_CODE+"?detail=1";
            ireturn = mHttpRequest.doPost(m_strURL, send, errorMessage);
            if (ireturn == HttpStatus.SC_OK) {
                ireturn = 0;
            } else{
                ireturn = getSendMsgErrMsg(ireturn,errorMessage);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            ireturn = R.string.nd_json_error;
        }
        return ireturn;
    }
    /**
     * 手机注册
     * <br>Created 2014-9-9 下午3:52:04
     * @param userInfo    用户信息
     * @param verifycode  手机短信验证码，必须
     * @param errorMessage 返回的消息
     * @return  201 注册成功 
     * 204 手机号码为空/昵称为空/密码为空/短信验证码为空/短信验证码不正确 
     * 416 手机已绑定，或者手机号码已经被注册为91通行证， 同时会返回uid与username 
     * 404 应用ID为空/应用ID不存在 
     * 406 已经绑定别名，无法注册/当前帐号已绑定且达到绑定个数，无法注册/帐号已存在，无法注册
     * 412 注册失败 
     * 409 注册失败，其他原因 
     * @author       gpy
    */
    public int regPhoneFrom99(UserInfo userInfo, String verifycode, StringBuilder errorMessage) {
        int ireturn = R.string.nd_reg_phone_error;
        if(null == userInfo){
            return ireturn;
        }
        
        JSONObject send = new JSONObject();
        try {
            send.put("appid", mAppid);
            send.put("phone", userInfo.getUserName());
            send.put("password", userInfo.getUserPass());
            send.put("verifycode", verifycode);
            send.put("blowfish", userInfo.getBlowfish());

            TelephonyManager tm = (TelephonyManager) (ApplicationVariable.INSTANCE.applicationContext.getSystemService(Context.TELEPHONY_SERVICE));
            String IMEI = tm.getDeviceId();

            send.put("imei", IMEI);
            send.put("sdklogin", "1");

            String m_strURL = BASE_REG_URL + ALIAS_REG_PHONE+"?detail=1";
            if(errorMessage==null){
                errorMessage = new StringBuilder();
            }
            ireturn = mHttpRequest.doPost(m_strURL, send, errorMessage);
            if (HttpStatus.SC_CREATED == ireturn) {
                ireturn = 0;
            }else{
                ireturn = getRegErrMsg(ireturn,errorMessage);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            ireturn = R.string.nd_json_error;
        }
        return ireturn;
    }
 

    /**
     * 改绑密保手机

     * <br>Created 2014-9-9 上午10:21:26
     * @param uid  必填，用户ID（11位整型）
     * @param oldPhone 必填，旧密保手机号码（11位整型）
     * @param newPhone  必填，新密保手机号码（11位整型）
     * @param verifycode 必填，手机验证码，需要先下发到用户手机（随机字符串）
     * @return 200 绑定密保手机成功;
     *         204 旧密保手机为空/新密保手机为空/短信验证码为空/短信验证码不正确;
     *         404 用户不存在;
     *         411 改绑密保手机失败 
     * @author       gpy
    */
    public int changePhone(long uid,String oldPhone,String newPhone,String verifycode) {
        try {
            JSONObject jsonSend = new JSONObject();
            jsonSend.put("uid", uid);
            jsonSend.put("oldphone", oldPhone);
            jsonSend.put("secphone", newPhone);
            jsonSend.put("verifycode", verifycode);
            String m_strURL = BASE_REG_URL + CHANGE_PHONE;
            StringBuilder receive = new StringBuilder();
            int ireturn = mHttpRequest.doPost(m_strURL, jsonSend, receive);
            if (HttpStatus.SC_OK == ireturn || HttpStatus.SC_NO_CONTENT == ireturn
                    || HttpStatus.SC_NOT_FOUND == ireturn|| HttpStatus.SC_LENGTH_REQUIRED == ireturn) {
                return ireturn ;
            } else {
                return HttpStatus.SC_LENGTH_REQUIRED ;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return HttpStatus.SC_LENGTH_REQUIRED ;

    }
    
    /**
     * 
     * <br>Created 2014-9-9 上午11:47:47
     * @param uid 必填，修改用户的帐户ID
     * @param sid 登录SID 
     * @param oldPwd 旧密码，6-12位字符
     * @param newPwd 新密码，6-12位字符
     * @param cfmPwd 确认密码，6-12位字符
     * @return 200 恭喜，密码重置成功 
     *         204 旧密码/新密码/确认密码 有空的情况 
     *         205 新密码和确认密码不同 
     *         304 旧密码错误 
     *         403 不属于特殊用户 
     *         404 用户不存在 
     *         406 新密码/确认密码/密码格式错误,允许6-12字符，可以包括数字,字母,区分大小写 
     *         417 用户不是登录状态 
     *         501 密码修改不成功 
     * @author       gpy
    */
    public int changePwd(long uid,String sid,String oldPwd,String newPwd,String cfmPwd) {
        try {
            JSONObject jsonSend = new JSONObject();
            jsonSend.put("oldpwd", oldPwd);
            jsonSend.put("newpwd", newPwd);
            jsonSend.put("cfmpwd", cfmPwd);
            StringBuilder strURL = new StringBuilder();
            strURL.append(BASE_REG_URL);
            strURL.append(CHANGE_PWD);
            strURL.append("/"+uid);
            strURL.append("?sid="+sid);
            StringBuilder receive = new StringBuilder();
            int ireturn = mHttpRequest.doPost(strURL.toString(), jsonSend, receive);
            if (HttpStatus.SC_OK == ireturn || HttpStatus.SC_NO_CONTENT == ireturn
                    || HttpStatus. SC_RESET_CONTENT == ireturn|| HttpStatus.SC_NOT_MODIFIED == ireturn
                    || HttpStatus.SC_NOT_FOUND == ireturn|| HttpStatus.SC_NOT_ACCEPTABLE == ireturn
                    || HttpStatus.SC_EXPECTATION_FAILED == ireturn|| HttpStatus.SC_NOT_IMPLEMENTED == ireturn) {
                return ireturn ;
            } else {
                return HttpStatus.SC_NOT_IMPLEMENTED;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return HttpStatus.SC_NOT_IMPLEMENTED;

    }
    /**
     * @Title: logOut
     * @Description: (登出)
     * @author Administrator
     * @date 2012-2-2 下午05:30:47
     * @param uid
     * @param sid
     * @return void
     * @throws
     */
    public void logOut(long uid, String sid) {
        String m_strURL = String.format("%s" + LOGOUT, getBaseHttpsUrl(), uid, sid);
        m_strURL = appendUapAppid(m_strURL);
        mHttpRequest.doPost(m_strURL, "", new StringBuilder());
    }

    /**
     * @Title: GetWlSid
     * @author Administrator
     * @date 2012-2-9 下午02:47:01
     * 
     * @param uid
     * @param siteid
     * @param receive
     * @return
     * @return int
     * @throws
     */
    public int getWlSid(long uid, int siteid, String sid, StringBuilder receive) {
        int ireturn = R.string.nd_get_wlsid_error;
        JSONObject send = new JSONObject();
        try {
            send.put("uid", Long.toString(uid));
            /* 1/91帐户(星火充值),2/星火帐户(星火充值),4/91帐户(算命充值), 必须 */
            send.put("siteid", Integer.toString(siteid));
            String m_strURL = getBaseHttpUrl() + String.format(CHARGE_URL, sid);
            m_strURL = appendUapAppid(m_strURL);
            ireturn = mHttpRequest.doPost(m_strURL, send, receive);
            if (ireturn != HttpStatus.SC_OK) {
                _getResponseErrMsg(receive);
            } else
                ireturn = 0;
        } catch (JSONException e) {
            e.printStackTrace();
            ireturn = R.string.nd_json_error;
        }
        return ireturn;
    }

    public int getUserInfo(long uid, String sid, StringBuilder receive) {
        int ireturn = R.string.nd_get_user_profile_error;
        String m_strURL = getBaseHttpUrl() + String.format(GET_USER_URL, uid, sid);
        m_strURL = appendUapAppid(m_strURL);
        ireturn = mHttpRequest.doGet(m_strURL, receive);
        if (ireturn != HttpStatus.SC_OK && ireturn != HttpStatus.SC_NOT_FOUND) {
            _getResponseErrMsg(receive);
        } else {
            ireturn = 0;
        }
        return ireturn;
    }

    public int checkSession(String sid, StringBuilder receive) {
        String m_strURL = getBaseHttpUrl() + String.format(CHECKSESSION_URL, sid);
        m_strURL = appendUapAppid(m_strURL);
        int ireturn = mHttpRequest.doGet(m_strURL, receive);
        if (ireturn != HttpStatus.SC_OK) {
            _getResponseErrMsg(receive);
        } else {
            ireturn = 0;
        }
        return ireturn;
    }

    /**
     * 解析信息
     * 
     * @param receive
     * @return
     */
    private void _getResponseErrMsg(StringBuilder receive) {
        if (receive.length() > 0) {
            try {
                JSONObject json = new JSONObject(receive.toString());
                if (json.has("msg")) {
                    receive.delete(0, receive.length());
                    receive.append(json.getString("msg"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 解析注册时，发送手机短信验证码返回值
     * <br>Created 2014-9-11 下午5:22:10
     * @param receive 返回值
     * @param iCode 返回码
     * @return 返回码
     * @author       gpy
    */
    private int getSendMsgErrMsg(final int iCode, StringBuilder receive) {
        int iReturn = iCode;
        if(receive==null){
            return iReturn;
        }
        if (receive.length() > 0) {
            try {
                JSONObject json = new JSONObject(receive.toString());
                receive.delete(0, receive.length());
                if (json.has("code")) {
                    iReturn =json.optInt("code");
                    switch (iReturn) {
                    case RegConst.REGIST_SEND_CODE_ID_LENGTH_ERR:
                        receive.append(mContext.getString(R.string.regist_send_code_id_length_err));
                        break;
                    case RegConst.REGIST_SEND_CODE_ID_FORMAT_ERR:
                        receive.append(mContext.getString(R.string.regist_send_code_id_format_err));
                        break;
                    case RegConst.REGIST_SEND_CODE_REGED_ERR:
                        receive.append(mContext.getString(R.string.regist_send_code_reged_err));
                        break;
                    case RegConst.REGIST_SEND_CODE_OVER_REGNUMBER_ERR:
                        receive.append(mContext.getString(R.string.regist_send_code_over_regnumber_err));
                        break;
                    case RegConst.REGIST_SEND_CODE_OTHER_REGED_ERR:
                        receive.append(mContext.getString(R.string.regist_send_code_other_reged_err));
                        break;
                    case RegConst.REGIST_SEND_CODE_SUCCESS:
                        receive.append(mContext.getString(R.string.regist_send_code_success));
                        break;
                    case RegConst.REGIST_SEND_CODE_OVER_SENDTIME_ERR:
                        receive.append(mContext.getString(R.string.regist_send_code_over_sendtime_err));
                        break;
                    case RegConst.REGIST_SEND_CODE_OVER_SENDNUMBER_ERR:
                        receive.append(mContext.getString(R.string.regist_send_code_over_sendnumber_err));
                        break;
                    case RegConst.REGIST_SEND_CODE_FAIL_ERR:
                        receive.append(mContext.getString(R.string.regist_send_code_fail_err));
                        break;
                    default:
                        break;
                    }
                }else{
                    receive.append(getUAPSendRegCodeErrMsgByRetCode(iReturn));
                }
            } catch (Exception e) {
                receive.append(mContext.getString(R.string.regist_fail_err));
                e.printStackTrace();
            }
        }
        return iReturn;
    }

    /**
     * 注册发送短信验证码时根据UAP返回的错误码映射错误消息
     * <br>Created 2014-9-11 下午5:22:10
     * @param iRet 返回码
     * @return UAP错误消息
     * @author       linsj
     */
    private String getUAPSendRegCodeErrMsgByRetCode(int iRet){
        if (HttpStatus.SC_OK == iRet){
            return "";
        }

        switch (iRet){
            case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
                return mContext.getString(R.string.regist_send_code_invalid_phone);
            default:
                return "";
        }
    }

    /**
     * 注册
     * <br>Created 2014-9-11 下午5:22:10
     * @param receive 返回值
     * @param iCode 返回码
     * @return 返回码
     * @author       gpy
    */
    private int getRegErrMsg(final int iCode, StringBuilder receive) {
        int iReturn = iCode;
        if(receive==null){
            return iReturn;
        }
        if (receive.length() > 0) {
            try {
                JSONObject json = new JSONObject(receive.toString());
                receive.delete(0, receive.length());
                if (json.has("code")) {
                    iReturn =json.optInt("code");
                    switch (iReturn) {
                    case RegConst.REGIST_SUBMIT_CODE_PWD_DECRYPTION_FAIL:
                        receive.append(mContext.getString(R.string.regist_submit_code_pwd_decryption_fail));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_PWD_LENGTH_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_pwd_length_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_PWD_TYPE_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_pwd_type_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_ENCRYPTED_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_encrypted_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_ID_CARD_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_id_card_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_REAL_NAME_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_real_name_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_PHONE_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_phone_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_ID_LENGTH_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_id_length_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_ID_TYPE_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_id_type_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_REGED_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_reged_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_REGNUMBER_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_regnumber_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_OTHER_REGED_ERR:
                        receive.append(mContext.getString(R.string.regist_submit_code_other_reged_err));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_REG_FAIL:
                        receive.append(mContext.getString(R.string.regist_submit_code_reg_fail));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_REG_UPDATE_SUCCESS:
                        receive.append(mContext.getString(R.string.regist_submit_code_reg_update_success));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_REG_UPDATE_FAIL:
                        receive.append(mContext.getString(R.string.regist_submit_code_reg_update_fail));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_GENERATE_FAIL:
                        receive.append(mContext.getString(R.string.regist_submit_code_generate_fail));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_PHONE_NOT_MATCH:
                        receive.append(mContext.getString(R.string.regist_submit_code_phone_not_match));
                        break;
                    case RegConst.REGIST_SUBMIT_CODE_MATCH_FAIL:
                        receive.append(mContext.getString(R.string.regist_submit_code_match_fail));
                        break;   
                    default:
                        break;
                    }
 
                }
            } catch (Exception e) {
                receive.append(mContext.getString(R.string.regist_fail_err));
                e.printStackTrace();
            }
        }
        return iReturn;
    }
    /**
     * 返回手机注册成功后信息
     * <br>Created 2014-9-19 上午9:44:12
     * @param userInfo 用户信息
     * @param errorMessage 服务端返回消息
     * @author       gpy
    */
    private void getRegSuccessMsg(UserInfo userInfo, StringBuilder receive) {
        if(receive==null){
            return ;
        }
        if (receive.length() > 0) {
            try {
                JSONObject json = new JSONObject(receive.toString());
                userInfo.setUapUid(json.optLong("uid"));
                userInfo.setSessionId(json.optString("sid"));
                userInfo.setUserNickName(json.optString("username"));
                userInfo.setTicket(json.optString("ticket"));
            } catch (JSONException e) {
                e.printStackTrace();
            } 
        }
    }
    public int getTicketByCookie(String cookie, String blowfish, UserInfo user,
            StringBuilder receive) {
        int iReturn = R.string.nd_json_error;
        String m_strURL = getBaseHttpUrl() + GET_TICKET_BY_COOKIE_URL;
//        m_strURL = appendUapAppid(m_strURL);
        JSONObject object = new JSONObject();
        try {
            object.put("appid", mAppid);
            object.put("blowfish", blowfish);
            object.put("cookie", cookie);
            object.put("tag", Configuration.TAG_ID);
            iReturn = mHttpRequest.doPost(m_strURL, object, receive);
            if (iReturn != HttpStatus.SC_OK) {
                // 200 登录成功
                // 400 认证 Cookie 为空/Userid 不能为空或0
                // 403 认证失败
                // 404 应用不存在
                // 503 应用暂停服务
                switch (iReturn) {
                case HttpStatus.SC_BAD_REQUEST:
                    // cookie为空
                    receive.delete(0, receive.length());
                    iReturn = R.string.nd_login_cookie_400;
                    break;
                case HttpStatus.SC_FORBIDDEN:
                    // 认证失败
                    receive.delete(0, receive.length());
                    iReturn = R.string.nd_login_cookie_403;
                    break;
                case HttpStatus.SC_NOT_FOUND:
                    // 应用不存在
                    receive.delete(0, receive.length());
                    iReturn = R.string.nd_login_cookie_404;
                    break;
                case HttpStatus.SC_SERVICE_UNAVAILABLE:
                    // 应用停止服务
                    receive.delete(0, receive.length());
                    iReturn = R.string.nd_login_cookie_503;
                    break;
                default:
                    _getResponseErrMsg(receive);
                    break;
                }
            } else {
                iReturn = 0;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return iReturn;
    }

    public int userLoginTicket(String ticket, String blowfish, StringBuilder receive) {
        int iReturn = R.string.nd_json_error;
        String m_strURL = getBaseHttpUrl() + TICKET_URL;
        m_strURL = appendUapAppid(m_strURL);
        JSONObject object = new JSONObject();
        try {
            object.put("appid", mAppid);
            object.put("blowfish", blowfish);
            object.put("ticket", ticket);
            object.put("tag", Configuration.TAG_ID);
            iReturn = mHttpRequest.doPost(m_strURL, object, receive);
            if (iReturn != HttpStatus.SC_OK) {
                switch (iReturn) {
                case HttpStatus.SC_BAD_REQUEST:
                    // cookie为空
                    receive.delete(0, receive.length());
                    iReturn = R.string.nd_login_process_error;
                    break;
                case HttpStatus.SC_FORBIDDEN:
                    // 认证失败
                    receive.delete(0, receive.length());
                    iReturn = R.string.nd_login_ticket_403;
                    break;
                case HttpStatus.SC_NOT_FOUND:
                    // 应用不存在
                    receive.delete(0, receive.length());
                    iReturn = R.string.nd_login_ticket_404;
                    break;
                default:
                    _getResponseErrMsg(receive);
                    break;
                }
            } else {
                iReturn = 0;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return iReturn;
    }
    
    /**
     * 取帐号状态接口
     * 
     * <br>Created 2014-10-23 下午2:19:06
     * @param account   帐号名
     * @param receive   接收的数据
     * @return
     * @author       张清荣
     */
    public int getAccountStatus(String account, StringBuilder receive) {
        int ireturn = R.string.nd_get_account_status_error;
        try {
            String m_strURL = BASE_REG_URL + GET_ACCOUNT_STATUS +"?account=" + account;
            ireturn = mHttpRequest.doGet(m_strURL, receive);
            if (ireturn != HttpStatus.SC_OK) {
                _getResponseErrMsg(receive);
            } else {
                ireturn = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ireturn;
    }
}
